<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>perlperf - Perl Performance and Optimization Techniques - Perldoc Browser</title>
    <link rel="search" href="https://perldoc.perl.org/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser">
    <link rel="canonical" href="https://perldoc.perl.org/perlperf">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" />
    <style>
      body {
        background: #f4f4f5;
        color: #020202;
      }
      .navbar-dark {
        background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%);
        background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0);
        background-repeat: repeat-x;
      }
      .navbar-dark .navbar-nav .nav-link,
      .navbar-dark .navbar-nav .nav-link:focus { color: #fff }
      .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 }
      #wrapperlicious {
        margin: 0 auto;
        font: 0.9em 'Helvetica Neue', Helvetica, sans-serif;
        font-weight: normal;
        line-height: 1.5em;
        margin: 0;
        padding: 0;
      }
      #wrapperlicious h1 { font-size: 1.5em }
      #wrapperlicious h2 { font-size: 1.3em }
      #wrapperlicious h3 { font-size: 1.1em }
      #wrapperlicious h4 { font-size: 0.9em }
      #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3,
      #wrapperlicious h4, #wrapperlicious dt {
        color: #020202;
        margin-top: 1em;
        margin-bottom: 1em;
        position: relative;
        font-weight: bold;
      }
      #wrapperlicious a { color: inherit; text-decoration: underline }
      #wrapperlicious #toc { text-decoration: none }
      #wrapperlicious a:hover { color: #2a2a2a }
      #wrapperlicious a img { border: 0 }
      #wrapperlicious :not(pre) > code {
        color: inherit;
        background-color: rgba(0, 0, 0, 0.04);
        border-radius: 3px;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        padding: 0.3em;
      }
      #wrapperlicious dd {
        margin: 0;
        margin-left: 2em;
      }
      #wrapperlicious dt {
        color: #2a2a2a;
        font-weight: bold;
        margin-left: 0.9em;
      }
      #wrapperlicious p {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious li > p {
        margin-bottom: 0;
        margin-top: 0;
      }
      #wrapperlicious pre {
        border: 1px solid #c1c1c1;
        border-radius: 3px;
        font: 100% Consolas, Menlo, Monaco, monospace;
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious pre > code {
        display: block;
        background-color: #f6f6f6;
        font: 0.9em Consolas, Menlo, Monaco, monospace;
        line-height: 1.5em;
        text-align: left;
        white-space: pre;
        padding: 1em;
      }
      #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul {
        margin-bottom: 1em;
        margin-top: 1em;
      }
      #wrapperlicious ul {
        list-style-type: square;
      }
      #wrapperlicious ul ul {
        margin-bottom: 0px;
        margin-top: 0px;
      }
      #footer {
        font-size: 0.8em;
        padding-top: 0.5em;
        text-align: center;
      }
      #more {
        display: inline;
        font-size: 0.8em;
      }
      #perldocdiv {
        background-color: #fff;
        border: 1px solid #c1c1c1;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        margin-left: auto;
        margin-right: auto;
        padding: 3em;
        padding-top: 1em;
        max-width: 960px;
      }
      #moduleversion { float: right }
      #wrapperlicious .leading-notice {
        font-style: italic;
        padding-left: 1em;
        margin-top: 1em;
        margin-bottom: 1em;
      }
      #wrapperlicious .permalink {
        display: none;
        left: -0.75em;
        position: absolute;
        padding-right: 0.25em;
        text-decoration: none;
      }
      #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink,
      #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink,
      #wrapperlicious dt:hover .permalink {
        display: block;
      }
    </style>
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-KVNWBNT5FB');
      gtag('config', 'UA-50555-3');
    </script>
  </head>
  <body>
    <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between">
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="https://perldoc.perl.org/">Perldoc Browser</a>
  <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlperf.html#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.35.0</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-stable">
          <a class="dropdown-item" href="https://perldoc.perl.org/perlperf">Latest</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.2/perlperf">5.38.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.1/perlperf">5.38.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0/perlperf">5.38.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.3/perlperf">5.36.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.2/perlperf">5.36.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.1/perlperf">5.36.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.36.0/perlperf">5.36.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.3/perlperf">5.34.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.2/perlperf">5.34.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.1/perlperf">5.34.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.34.0/perlperf">5.34.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.1/perlperf">5.32.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.32.0/perlperf">5.32.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.3/perlperf">5.30.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.2/perlperf">5.30.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.1/perlperf">5.30.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.30.0/perlperf">5.30.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.3/perlperf">5.28.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.2/perlperf">5.28.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.1/perlperf">5.28.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.28.0/perlperf">5.28.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.3/perlperf">5.26.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.2/perlperf">5.26.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.1/perlperf">5.26.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.26.0/perlperf">5.26.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.4/perlperf">5.24.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.3/perlperf">5.24.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.2/perlperf">5.24.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.1/perlperf">5.24.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.24.0/perlperf">5.24.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.4/perlperf">5.22.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.3/perlperf">5.22.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.2/perlperf">5.22.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.1/perlperf">5.22.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.22.0/perlperf">5.22.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.3/perlperf">5.20.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.2/perlperf">5.20.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.1/perlperf">5.20.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.20.0/perlperf">5.20.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.4/perlperf">5.18.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.3/perlperf">5.18.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.2/perlperf">5.18.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.1/perlperf">5.18.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.18.0/perlperf">5.18.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.3/perlperf">5.16.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.2/perlperf">5.16.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.1/perlperf">5.16.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.16.0/perlperf">5.16.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.4/perlperf">5.14.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.3/perlperf">5.14.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.2/perlperf">5.14.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.1/perlperf">5.14.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.14.0/perlperf">5.14.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.5/perlperf">5.12.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.4/perlperf">5.12.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.3/perlperf">5.12.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.2/perlperf">5.12.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.1/perlperf">5.12.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.12.0/perlperf">5.12.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.1/perlperf">5.10.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.10.0/perlperf">5.10.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.9/perlperf">5.8.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.8/perlperf">5.8.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.7/perlperf">5.8.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.6/perlperf">5.8.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.5/perlperf">5.8.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.4/perlperf">5.8.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.3/perlperf">5.8.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.2/perlperf">5.8.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.1/perlperf">5.8.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.8.0/perlperf">5.8.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.2/perlperf">5.6.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.1/perlperf">5.6.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.6.0/perlperf">5.6.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_04/perlperf">5.005_04</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_03/perlperf">5.005_03</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_02/perlperf">5.005_02</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005_01/perlperf">5.005_01</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.005/perlperf">5.005</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlperf.html#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-dev">
          <a class="dropdown-item" href="https://perldoc.perl.org/blead/perlperf">blead</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.6/perlperf">5.39.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.5/perlperf">5.39.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.4/perlperf">5.39.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.3/perlperf">5.39.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.2/perlperf">5.39.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.39.1/perlperf">5.39.1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC2/perlperf">5.38.0-RC2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.38.0-RC1/perlperf">5.38.0-RC1</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.11/perlperf">5.37.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.10/perlperf">5.37.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.9/perlperf">5.37.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.8/perlperf">5.37.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.7/perlperf">5.37.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.6/perlperf">5.37.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.5/perlperf">5.37.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.4/perlperf">5.37.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.3/perlperf">5.37.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.2/perlperf">5.37.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.1/perlperf">5.37.1</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.37.0/perlperf">5.37.0</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.11/perlperf">5.35.11</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.10/perlperf">5.35.10</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.9/perlperf">5.35.9</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.8/perlperf">5.35.8</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.7/perlperf">5.35.7</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.6/perlperf">5.35.6</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.5/perlperf">5.35.5</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.4/perlperf">5.35.4</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.3/perlperf">5.35.3</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.2/perlperf">5.35.2</a>
          <a class="dropdown-item" href="https://perldoc.perl.org/5.35.1/perlperf">5.35.1</a>
          <a class="dropdown-item active" href="perlperf.html">5.35.0</a>
        </div>
      </li>
      <li class="nav-item dropdown text-nowrap">
        <a class="nav-link dropdown-toggle" href="perlperf.html#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a>
        <div class="dropdown-menu" aria-labelledby="dropdownlink-nav">
          <a class="dropdown-item" href="perl.html">Perl</a>
          <a class="dropdown-item" href="perlintro.html">Intro</a>
          <a class="dropdown-item" href="perl.html#Tutorials">Tutorials</a>
          <a class="dropdown-item" href="perlfaq.html">FAQs</a>
          <a class="dropdown-item" href="perl.html#Reference-Manual">Reference</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlop.html">Operators</a>
          <a class="dropdown-item" href="functions.html">Functions</a>
          <a class="dropdown-item" href="variables.html">Variables</a>
          <a class="dropdown-item" href="modules.html">Modules</a>
          <a class="dropdown-item" href="perlutil.html">Utilities</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="perlcommunity.html">Community</a>
          <a class="dropdown-item" href="perlhist.html">History</a>
        </div>
      </li>
    </ul>
    <ul class="navbar-nav">
      <script>
        function set_expand (expand) {
          var perldocdiv = document.getElementById('perldocdiv');
          var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width');
          var expanded = (width == '' || width == 'none') ? true : false;
          if (expand === null) {
            expand = !expanded;
          }
          if ((expand && !expanded) || (!expand && expanded)) {
            perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px');
            var button_classlist = document.getElementById('content-expand-button').classList;
            if (expand) {
              button_classlist.add('btn-light');
              button_classlist.remove('btn-outline-light');
            } else {
              button_classlist.add('btn-outline-light');
              button_classlist.remove('btn-light');
            }
          }
          return expand;
        }
        function toggle_expand () {
          var expand = set_expand(null);
          document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC';
        }
        function read_expand () {
          return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 });
        }
        if (document.readyState === 'loading') {
          document.addEventListener('DOMContentLoaded', function () {
            if (read_expand()) {
              set_expand(true);
            }
          });
        } else if (read_expand()) {
          set_expand(true);
        }
      </script>
      <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-2" onclick="toggle_expand()">Expand</button>
    <ul>
    <form class="form-inline" method="get" action="https://perldoc.perl.org/5.35.0/search">
      <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search">
    </form>
  </div>
</nav>

    <div id="wrapperlicious" class="container-fluid">
      <div id="perldocdiv">
        <div id="links">
          <a href="perlperf.html">perlperf</a>
          <div id="more">
            (<a href="perlperf.txt">source</a>,
            <a href="https://metacpan.org/pod/perlperf">CPAN</a>)
          </div>
        </div>
        <div class="leading-notice">
          You are viewing the version of this documentation from Perl 5.35.0.
            This is a development version of Perl.
        </div>
        <h1><a id="toc">CONTENTS</a></h1>
                  <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#NAME">NAME</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#DESCRIPTION">DESCRIPTION</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#OVERVIEW">OVERVIEW</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#ONE-STEP-SIDEWAYS">ONE STEP SIDEWAYS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#ONE-STEP-FORWARD">ONE STEP FORWARD</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#ANOTHER-STEP-SIDEWAYS">ANOTHER STEP SIDEWAYS</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#GENERAL-GUIDELINES">GENERAL GUIDELINES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#BENCHMARKS">BENCHMARKS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Assigning-and-Dereferencing-Variables.">Assigning and Dereferencing Variables.</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Search-and-replace-or-tr">Search and replace or tr</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#PROFILING-TOOLS">PROFILING TOOLS</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Devel::DProf">Devel::DProf</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Devel::Profiler">Devel::Profiler</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Devel::SmallProf">Devel::SmallProf</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Devel::FastProf">Devel::FastProf</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Devel::NYTProf">Devel::NYTProf</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#SORTING">SORTING</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#LOGGING">LOGGING</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#Logging-if-DEBUG-(constant)">Logging if DEBUG (constant)</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#POSTSCRIPT">POSTSCRIPT</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#SEE-ALSO">SEE ALSO</a>
                            <ul>
              <li>
                <a class="text-decoration-none" href="perlperf.html#PERLDOCS">PERLDOCS</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#MAN-PAGES">MAN PAGES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#MODULES">MODULES</a>
              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#URLS">URLS</a>
              </li>
          </ul>

              </li>
              <li>
                <a class="text-decoration-none" href="perlperf.html#AUTHOR">AUTHOR</a>
              </li>
          </ul>

      <h1 id="NAME"><a class="permalink" href="perlperf.html#NAME">#</a>NAME</h1>

<p>perlperf - Perl Performance and Optimization Techniques</p>

<h1 id="DESCRIPTION"><a class="permalink" href="perlperf.html#DESCRIPTION">#</a>DESCRIPTION</h1>

<p>This is an introduction to the use of performance and optimization techniques which can be used with particular reference to perl programs. While many perl developers have come from other languages, and can use their prior knowledge where appropriate, there are many other people who might benefit from a few perl specific pointers. If you want the condensed version, perhaps the best advice comes from the renowned Japanese Samurai, Miyamoto Musashi, who said:</p>

<pre><code class="plaintext">&quot;Do Not Engage in Useless Activity&quot;</code></pre>

<p>in 1645.</p>

<h1 id="OVERVIEW"><a class="permalink" href="perlperf.html#OVERVIEW">#</a>OVERVIEW</h1>

<p>Perhaps the most common mistake programmers make is to attempt to optimize their code before a program actually does anything useful - this is a bad idea. There&#39;s no point in having an extremely fast program that doesn&#39;t work. The first job is to get a program to <i>correctly</i> do something <b>useful</b>, (not to mention ensuring the test suite is fully functional), and only then to consider optimizing it. Having decided to optimize existing working code, there are several simple but essential steps to consider which are intrinsic to any optimization process.</p>

<h2 id="ONE-STEP-SIDEWAYS"><a class="permalink" href="perlperf.html#ONE-STEP-SIDEWAYS">#</a><a id="ONE"></a>ONE STEP SIDEWAYS</h2>

<p>Firstly, you need to establish a baseline time for the existing code, which timing needs to be reliable and repeatable. You&#39;ll probably want to use the <code>Benchmark</code> or <code>Devel::NYTProf</code> modules, or something similar, for this step, or perhaps the Unix system <code>time</code> utility, whichever is appropriate. See the base of this document for a longer list of benchmarking and profiling modules, and recommended further reading.</p>

<h2 id="ONE-STEP-FORWARD"><a class="permalink" href="perlperf.html#ONE-STEP-FORWARD">#</a><a id="ONE1"></a>ONE STEP FORWARD</h2>

<p>Next, having examined the program for <i>hot spots</i>, (places where the code seems to run slowly), change the code with the intention of making it run faster. Using version control software, like <code>subversion</code>, will ensure no changes are irreversible. It&#39;s too easy to fiddle here and fiddle there - don&#39;t change too much at any one time or you might not discover which piece of code <b>really</b> was the slow bit.</p>

<h2 id="ANOTHER-STEP-SIDEWAYS"><a class="permalink" href="perlperf.html#ANOTHER-STEP-SIDEWAYS">#</a><a id="ANOTHER"></a>ANOTHER STEP SIDEWAYS</h2>

<p>It&#39;s not enough to say: &quot;that will make it run faster&quot;, you have to check it. Rerun the code under control of the benchmarking or profiling modules, from the first step above, and check that the new code executed the <b>same task</b> in <i>less time</i>. Save your work and repeat...</p>

<h1 id="GENERAL-GUIDELINES"><a class="permalink" href="perlperf.html#GENERAL-GUIDELINES">#</a><a id="GENERAL"></a>GENERAL GUIDELINES</h1>

<p>The critical thing when considering performance is to remember there is no such thing as a <code>Golden Bullet</code>, which is why there are no rules, only guidelines.</p>

<p>It is clear that inline code is going to be faster than subroutine or method calls, because there is less overhead, but this approach has the disadvantage of being less maintainable and comes at the cost of greater memory usage - there is no such thing as a free lunch. If you are searching for an element in a list, it can be more efficient to store the data in a hash structure, and then simply look to see whether the key is defined, rather than to loop through the entire array using grep() for instance. substr() may be (a lot) faster than grep() but not as flexible, so you have another trade-off to access. Your code may contain a line which takes 0.01 of a second to execute which if you call it 1,000 times, quite likely in a program parsing even medium sized files for instance, you already have a 10 second delay, in just one single code location, and if you call that line 100,000 times, your entire program will slow down to an unbearable crawl.</p>

<p>Using a subroutine as part of your sort is a powerful way to get exactly what you want, but will usually be slower than the built-in <i>alphabetic</i> <code>cmp</code> and <i>numeric</i> <code>&lt;=&gt;</code> sort operators. It is possible to make multiple passes over your data, building indices to make the upcoming sort more efficient, and to use what is known as the <code>OM</code> (Orcish Maneuver) to cache the sort keys in advance. The cache lookup, while a good idea, can itself be a source of slowdown by enforcing a double pass over the data - once to setup the cache, and once to sort the data. Using <code>pack()</code> to extract the required sort key into a consistent string can be an efficient way to build a single string to compare, instead of using multiple sort keys, which makes it possible to use the standard, written in <code>c</code> and fast, perl <code>sort()</code> function on the output, and is the basis of the <code>GRT</code> (Guttman Rossler Transform). Some string combinations can slow the <code>GRT</code> down, by just being too plain complex for its own good.</p>

<p>For applications using database backends, the standard <code>DBIx</code> namespace has tries to help with keeping things nippy, not least because it tries to <i>not</i> query the database until the latest possible moment, but always read the docs which come with your choice of libraries. Among the many issues facing developers dealing with databases should remain aware of is to always use <code>SQL</code> placeholders and to consider pre-fetching data sets when this might prove advantageous. Splitting up a large file by assigning multiple processes to parsing a single file, using say <code>POE</code>, <code>threads</code> or <code>fork</code> can also be a useful way of optimizing your usage of the available <code>CPU</code> resources, though this technique is fraught with concurrency issues and demands high attention to detail.</p>

<p>Every case has a specific application and one or more exceptions, and there is no replacement for running a few tests and finding out which method works best for your particular environment, this is why writing optimal code is not an exact science, and why we love using Perl so much - TMTOWTDI.</p>

<h1 id="BENCHMARKS"><a class="permalink" href="perlperf.html#BENCHMARKS">#</a>BENCHMARKS</h1>

<p>Here are a few examples to demonstrate usage of Perl&#39;s benchmarking tools.</p>

<h2 id="Assigning-and-Dereferencing-Variables."><a class="permalink" href="perlperf.html#Assigning-and-Dereferencing-Variables.">#</a><a id="Assigning"></a><a id="Assigning-and-Dereferencing-Variables"></a>Assigning and Dereferencing Variables.</h2>

<p>I&#39;m sure most of us have seen code which looks like, (or worse than), this:</p>

<pre><code>if ( $obj-&gt;{_ref}-&gt;{_myscore} &gt;= $obj-&gt;{_ref}-&gt;{_yourscore} ) {
    ...</code></pre>

<p>This sort of code can be a real eyesore to read, as well as being very sensitive to typos, and it&#39;s much clearer to dereference the variable explicitly. We&#39;re side-stepping the issue of working with object-oriented programming techniques to encapsulate variable access via methods, only accessible through an object. Here we&#39;re just discussing the technical implementation of choice, and whether this has an effect on performance. We can see whether this dereferencing operation, has any overhead by putting comparative code in a file and running a <code>Benchmark</code> test.</p>

<p># dereference</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

use Benchmark;

my $ref = {
        &#39;ref&#39;   =&gt; {
            _myscore    =&gt; &#39;100 + 1&#39;,
            _yourscore  =&gt; &#39;102 - 1&#39;,
        },
};

timethese(1000000, {
        &#39;direct&#39;       =&gt; sub {
          my $x = $ref-&gt;{ref}-&gt;{_myscore} . $ref-&gt;{ref}-&gt;{_yourscore} ;
        },
        &#39;dereference&#39;  =&gt; sub {
            my $ref  = $ref-&gt;{ref};
            my $myscore = $ref-&gt;{_myscore};
            my $yourscore = $ref-&gt;{_yourscore};
            my $x = $myscore . $yourscore;
        },
});</code></pre>

<p>It&#39;s essential to run any timing measurements a sufficient number of times so the numbers settle on a numerical average, otherwise each run will naturally fluctuate due to variations in the environment, to reduce the effect of contention for <code>CPU</code> resources and network bandwidth for instance. Running the above code for one million iterations, we can take a look at the report output by the <code>Benchmark</code> module, to see which approach is the most effective.</p>

<pre><code class="plaintext">$&gt; perl dereference

Benchmark: timing 1000000 iterations of dereference, direct...
dereference:  2 wallclock secs ( 1.59 usr +  0.00 sys =  1.59 CPU) @ 628930.82/s (n=1000000)
    direct:  1 wallclock secs ( 1.20 usr +  0.00 sys =  1.20 CPU) @ 833333.33/s (n=1000000)</code></pre>

<p>The difference is clear to see and the dereferencing approach is slower. While it managed to execute an average of 628,930 times a second during our test, the direct approach managed to run an additional 204,403 times, unfortunately. Unfortunately, because there are many examples of code written using the multiple layer direct variable access, and it&#39;s usually horrible. It is, however, minusculy faster. The question remains whether the minute gain is actually worth the eyestrain, or the loss of maintainability.</p>

<h2 id="Search-and-replace-or-tr"><a class="permalink" href="perlperf.html#Search-and-replace-or-tr">#</a><a id="Search"></a>Search and replace or tr</h2>

<p>If we have a string which needs to be modified, while a regex will almost always be much more flexible, <code>tr</code>, an oft underused tool, can still be a useful. One scenario might be replace all vowels with another character. The regex solution might look like this:</p>

<pre><code>$str =~ s/[aeiou]/x/g</code></pre>

<p>The <code>tr</code> alternative might look like this:</p>

<pre><code>$str =~ tr/aeiou/xxxxx/</code></pre>

<p>We can put that into a test file which we can run to check which approach is the fastest, using a global <code>$STR</code> variable to assign to the <code>my $str</code> variable so as to avoid perl trying to optimize any of the work away by noticing it&#39;s assigned only the once.</p>

<p># regex-transliterate</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

use Benchmark;

my $STR = &quot;$$-this and that&quot;;

timethese( 1000000, {
&#39;sr&#39;  =&gt; sub { my $str = $STR; $str =~ s/[aeiou]/x/g; return $str; },
&#39;tr&#39;  =&gt; sub { my $str = $STR; $str =~ tr/aeiou/xxxxx/; return $str; },
});</code></pre>

<p>Running the code gives us our results:</p>

<pre><code class="plaintext">$&gt; perl regex-transliterate

Benchmark: timing 1000000 iterations of sr, tr...
        sr:  2 wallclock secs ( 1.19 usr +  0.00 sys =  1.19 CPU) @ 840336.13/s (n=1000000)
        tr:  0 wallclock secs ( 0.49 usr +  0.00 sys =  0.49 CPU) @ 2040816.33/s (n=1000000)</code></pre>

<p>The <code>tr</code> version is a clear winner. One solution is flexible, the other is fast - and it&#39;s appropriately the programmer&#39;s choice which to use.</p>

<p>Check the <code>Benchmark</code> docs for further useful techniques.</p>

<h1 id="PROFILING-TOOLS"><a class="permalink" href="perlperf.html#PROFILING-TOOLS">#</a><a id="PROFILING"></a>PROFILING TOOLS</h1>

<p>A slightly larger piece of code will provide something on which a profiler can produce more extensive reporting statistics. This example uses the simplistic <code>wordmatch</code> program which parses a given input file and spews out a short report on the contents.</p>

<p># wordmatch</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

=head1 NAME

filewords - word analysis of input file

=head1 SYNOPSIS

    filewords -f inputfilename [-d]

=head1 DESCRIPTION

This program parses the given filename, specified with C&lt;-f&gt;, and
displays a simple analysis of the words found therein.  Use the C&lt;-d&gt;
switch to enable debugging messages.

=cut

use FileHandle;
use Getopt::Long;

my $debug   =  0;
my $file    = &#39;&#39;;

my $result = GetOptions (
    &#39;debug&#39;         =&gt; \$debug,
    &#39;file=s&#39;        =&gt; \$file,
);
die(&quot;invalid args&quot;) unless $result;

unless ( -f $file ) {
    die(&quot;Usage: $0 -f filename [-d]&quot;);
}
my $FH = FileHandle-&gt;new(&quot;&lt; $file&quot;)
                              or die(&quot;unable to open file($file): $!&quot;);

my $i_LINES = 0;
my $i_WORDS = 0;
my %count   = ();

my @lines = &lt;$FH&gt;;
foreach my $line ( @lines ) {
    $i_LINES++;
    $line =~ s/\n//;
    my @words = split(/ +/, $line);
    my $i_words = scalar(@words);
    $i_WORDS = $i_WORDS + $i_words;
    debug(&quot;line: $i_LINES supplying $i_words words: @words&quot;);
    my $i_word = 0;
    foreach my $word ( @words ) {
        $i_word++;
        $count{$i_LINES}{spec} += matches($i_word, $word,
                                          &#39;[^a-zA-Z0-9]&#39;);
        $count{$i_LINES}{only} += matches($i_word, $word,
                                          &#39;^[^a-zA-Z0-9]+$&#39;);
        $count{$i_LINES}{cons} += matches($i_word, $word,
                                    &#39;^[(?i:bcdfghjklmnpqrstvwxyz)]+$&#39;);
        $count{$i_LINES}{vows} += matches($i_word, $word,
                                          &#39;^[(?i:aeiou)]+$&#39;);
        $count{$i_LINES}{caps} += matches($i_word, $word,
                                          &#39;^[(A-Z)]+$&#39;);
    }
}

print report( %count );

sub matches {
    my $i_wd  = shift;
    my $word  = shift;
    my $regex = shift;
    my $has = 0;

    if ( $word =~ /($regex)/ ) {
        $has++ if $1;
    }

    debug( &quot;word: $i_wd &quot;
          . ($has ? &#39;matches&#39; : &#39;does not match&#39;)
          . &quot; chars: /$regex/&quot;);

    return $has;
}

sub report {
    my %report = @_;
    my %rep;

    foreach my $line ( keys %report ) {
        foreach my $key ( keys $report{$line}-&gt;%* ) {
            $rep{$key} += $report{$line}{$key};
        }
    }

    my $report = qq|
$0 report for $file:
lines in file: $i_LINES
words in file: $i_WORDS
words with special (non-word) characters: $i_spec
words with only special (non-word) characters: $i_only
words with only consonants: $i_cons
words with only capital letters: $i_caps
words with only vowels: $i_vows
|;

    return $report;
}

sub debug {
    my $message = shift;

    if ( $debug ) {
        print STDERR &quot;DBG: $message\n&quot;;
    }
}

exit 0;</code></pre>

<h2 id="Devel::DProf"><a class="permalink" href="perlperf.html#Devel::DProf">#</a><a id="Devel"></a>Devel::DProf</h2>

<p>This venerable module has been the de-facto standard for Perl code profiling for more than a decade, but has been replaced by a number of other modules which have brought us back to the 21st century. Although you&#39;re recommended to evaluate your tool from the several mentioned here and from the CPAN list at the base of this document, (and currently <a href="./Devel::NYTProf.html">Devel::NYTProf</a> seems to be the weapon of choice - see below), we&#39;ll take a quick look at the output from <a href="./Devel::DProf.html">Devel::DProf</a> first, to set a baseline for Perl profiling tools. Run the above program under the control of <code>Devel::DProf</code> by using the <code>-d</code> switch on the command-line.</p>

<pre><code class="plaintext">$&gt; perl -d:DProf wordmatch -f perl5db.pl

&lt;...multiple lines snipped...&gt;

wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701</code></pre>

<p><code>Devel::DProf</code> produces a special file, called <i>tmon.out</i> by default, and this file is read by the <code>dprofpp</code> program, which is already installed as part of the <code>Devel::DProf</code> distribution. If you call <code>dprofpp</code> with no options, it will read the <i>tmon.out</i> file in the current directory and produce a human readable statistics report of the run of your program. Note that this may take a little time.</p>

<pre><code>$&gt; dprofpp

Total Elapsed Time = 2.951677 Seconds
  User+System Time = 2.871677 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c  Name
 102.   2.945  3.003 251215   0.0000 0.0000  main::matches
 2.40   0.069  0.069 260643   0.0000 0.0000  main::debug
 1.74   0.050  0.050      1   0.0500 0.0500  main::report
 1.04   0.030  0.049      4   0.0075 0.0123  main::BEGIN
 0.35   0.010  0.010      3   0.0033 0.0033  Exporter::as_heavy
 0.35   0.010  0.010      7   0.0014 0.0014  IO::File::BEGIN
 0.00       - -0.000      1        -      -  Getopt::Long::FindOption
 0.00       - -0.000      1        -      -  Symbol::BEGIN
 0.00       - -0.000      1        -      -  Fcntl::BEGIN
 0.00       - -0.000      1        -      -  Fcntl::bootstrap
 0.00       - -0.000      1        -      -  warnings::BEGIN
 0.00       - -0.000      1        -      -  IO::bootstrap
 0.00       - -0.000      1        -      -  Getopt::Long::ConfigDefaults
 0.00       - -0.000      1        -      -  Getopt::Long::Configure
 0.00       - -0.000      1        -      -  Symbol::gensym</code></pre>

<p><code>dprofpp</code> will produce some quite detailed reporting on the activity of the <code>wordmatch</code> program. The wallclock, user and system, times are at the top of the analysis, and after this are the main columns defining which define the report. Check the <code>dprofpp</code> docs for details of the many options it supports.</p>

<p>See also <code><a href="./Apache::DProf.html">Apache::DProf</a></code> which hooks <code>Devel::DProf</code> into <code>mod_perl</code>.</p>

<h2 id="Devel::Profiler"><a class="permalink" href="perlperf.html#Devel::Profiler">#</a><a id="Devel1"></a>Devel::Profiler</h2>

<p>Let&#39;s take a look at the same program using a different profiler: <code>Devel::Profiler</code>, a drop-in Perl-only replacement for <code>Devel::DProf</code>. The usage is very slightly different in that instead of using the special <code>-d:</code> flag, you pull <code>Devel::Profiler</code> in directly as a module using <code>-M</code>.</p>

<pre><code class="plaintext">$&gt; perl -MDevel::Profiler wordmatch -f perl5db.pl

&lt;...multiple lines snipped...&gt;

wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701</code></pre>

<p><code>Devel::Profiler</code> generates a tmon.out file which is compatible with the <code>dprofpp</code> program, thus saving the construction of a dedicated statistics reader program. <code>dprofpp</code> usage is therefore identical to the above example.</p>

<pre><code>$&gt; dprofpp

Total Elapsed Time =   20.984 Seconds
  User+System Time =   19.981 Seconds
Exclusive Times
%Time ExclSec CumulS #Calls sec/call Csec/c  Name
 49.0   9.792 14.509 251215   0.0000 0.0001  main::matches
 24.4   4.887  4.887 260643   0.0000 0.0000  main::debug
 0.25   0.049  0.049      1   0.0490 0.0490  main::report
 0.00   0.000  0.000      1   0.0000 0.0000  Getopt::Long::GetOptions
 0.00   0.000  0.000      2   0.0000 0.0000  Getopt::Long::ParseOptionSpec
 0.00   0.000  0.000      1   0.0000 0.0000  Getopt::Long::FindOption
 0.00   0.000  0.000      1   0.0000 0.0000  IO::File::new
 0.00   0.000  0.000      1   0.0000 0.0000  IO::Handle::new
 0.00   0.000  0.000      1   0.0000 0.0000  Symbol::gensym
 0.00   0.000  0.000      1   0.0000 0.0000  IO::File::open</code></pre>

<p>Interestingly we get slightly different results, which is mostly because the algorithm which generates the report is different, even though the output file format was allegedly identical. The elapsed, user and system times are clearly showing the time it took for <code>Devel::Profiler</code> to execute its own run, but the column listings feel more accurate somehow than the ones we had earlier from <code>Devel::DProf</code>. The 102% figure has disappeared, for example. This is where we have to use the tools at our disposal, and recognise their pros and cons, before using them. Interestingly, the numbers of calls for each subroutine are identical in the two reports, it&#39;s the percentages which differ. As the author of <code>Devel::Proviler</code> writes:</p>

<pre><code class="plaintext">...running HTML::Template&#39;s test suite under Devel::DProf shows
output() taking NO time but Devel::Profiler shows around 10% of the
time is in output().  I don&#39;t know which to trust but my gut tells me
something is wrong with Devel::DProf.  HTML::Template::output() is a
big routine that&#39;s called for every test. Either way, something needs
fixing.</code></pre>

<p>YMMV.</p>

<p>See also <code><a href="https://perldoc.perl.org/5.35.0/Devel::Apache::Profiler">Devel::Apache::Profiler</a></code> which hooks <code>Devel::Profiler</code> into <code>mod_perl</code>.</p>

<h2 id="Devel::SmallProf"><a class="permalink" href="perlperf.html#Devel::SmallProf">#</a><a id="Devel2"></a>Devel::SmallProf</h2>

<p>The <code>Devel::SmallProf</code> profiler examines the runtime of your Perl program and produces a line-by-line listing to show how many times each line was called, and how long each line took to execute. It is called by supplying the familiar <code>-d</code> flag to Perl at runtime.</p>

<pre><code class="plaintext">$&gt; perl -d:SmallProf wordmatch -f perl5db.pl

&lt;...multiple lines snipped...&gt;

wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701</code></pre>

<p><code>Devel::SmallProf</code> writes it&#39;s output into a file called <i>smallprof.out</i>, by default. The format of the file looks like this:</p>

<pre><code class="plaintext">&lt;num&gt; &lt;time&gt; &lt;ctime&gt; &lt;line&gt;:&lt;text&gt;</code></pre>

<p>When the program has terminated, the output may be examined and sorted using any standard text filtering utilities. Something like the following may be sufficient:</p>

<pre><code>$&gt; cat smallprof.out | grep \d*: | sort -k3 | tac | head -n20

251215   1.65674   7.68000    75: if ( $word =~ /($regex)/ ) {
251215   0.03264   4.40000    79: debug(&quot;word: $i_wd &quot;.($has ? &#39;matches&#39; :
251215   0.02693   4.10000    81: return $has;
260643   0.02841   4.07000   128: if ( $debug ) {
260643   0.02601   4.04000   126: my $message = shift;
251215   0.02641   3.91000    73: my $has = 0;
251215   0.03311   3.71000    70: my $i_wd  = shift;
251215   0.02699   3.69000    72: my $regex = shift;
251215   0.02766   3.68000    71: my $word  = shift;
 50243   0.59726   1.00000    59:  $count{$i_LINES}{cons} =
 50243   0.48175   0.92000    61:  $count{$i_LINES}{spec} =
 50243   0.00644   0.89000    56:  my $i_cons = matches($i_word, $word,
 50243   0.48837   0.88000    63:  $count{$i_LINES}{caps} =
 50243   0.00516   0.88000    58:  my $i_caps = matches($i_word, $word, &#39;^[(A-
 50243   0.00631   0.81000    54:  my $i_spec = matches($i_word, $word, &#39;[^a-
 50243   0.00496   0.80000    57:  my $i_vows = matches($i_word, $word,
 50243   0.00688   0.80000    53:  $i_word++;
 50243   0.48469   0.79000    62:  $count{$i_LINES}{only} =
 50243   0.48928   0.77000    60:  $count{$i_LINES}{vows} =
 50243   0.00683   0.75000    55:  my $i_only = matches($i_word, $word, &#39;^[^a-</code></pre>

<p>You can immediately see a slightly different focus to the subroutine profiling modules, and we start to see exactly which line of code is taking the most time. That regex line is looking a bit suspicious, for example. Remember that these tools are supposed to be used together, there is no single best way to profile your code, you need to use the best tools for the job.</p>

<p>See also <code><a href="./Apache::SmallProf.html">Apache::SmallProf</a></code> which hooks <code>Devel::SmallProf</code> into <code>mod_perl</code>.</p>

<h2 id="Devel::FastProf"><a class="permalink" href="perlperf.html#Devel::FastProf">#</a><a id="Devel3"></a>Devel::FastProf</h2>

<p><code>Devel::FastProf</code> is another Perl line profiler. This was written with a view to getting a faster line profiler, than is possible with for example <code>Devel::SmallProf</code>, because it&#39;s written in <code>C</code>. To use <code>Devel::FastProf</code>, supply the <code>-d</code> argument to Perl:</p>

<pre><code class="plaintext">$&gt; perl -d:FastProf wordmatch -f perl5db.pl

&lt;...multiple lines snipped...&gt;

wordmatch report for perl5db.pl:
lines in file: 9428
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701</code></pre>

<p><code>Devel::FastProf</code> writes statistics to the file <i>fastprof.out</i> in the current directory. The output file, which can be specified, can be interpreted by using the <code>fprofpp</code> command-line program.</p>

<pre><code>$&gt; fprofpp | head -n20

# fprofpp output format is:
# filename:line time count: source
wordmatch:75 3.93338 251215: if ( $word =~ /($regex)/ ) {
wordmatch:79 1.77774 251215: debug(&quot;word: $i_wd &quot;.($has ? &#39;matches&#39; : &#39;does not match&#39;).&quot; chars: /$regex/&quot;);
wordmatch:81 1.47604 251215: return $has;
wordmatch:126 1.43441 260643: my $message = shift;
wordmatch:128 1.42156 260643: if ( $debug ) {
wordmatch:70 1.36824 251215: my $i_wd  = shift;
wordmatch:71 1.36739 251215: my $word  = shift;
wordmatch:72 1.35939 251215: my $regex = shift;</code></pre>

<p>Straightaway we can see that the number of times each line has been called is identical to the <code>Devel::SmallProf</code> output, and the sequence is only very slightly different based on the ordering of the amount of time each line took to execute, <code>if ( $debug ) { </code> and <code>my $message = shift;</code>, for example. The differences in the actual times recorded might be in the algorithm used internally, or it could be due to system resource limitations or contention.</p>

<p>See also the <a href="./DBIx::Profile.html">DBIx::Profile</a> which will profile database queries running under the <code>DBIx::*</code> namespace.</p>

<h2 id="Devel::NYTProf"><a class="permalink" href="perlperf.html#Devel::NYTProf">#</a><a id="Devel4"></a>Devel::NYTProf</h2>

<p><code>Devel::NYTProf</code> is the <b>next generation</b> of Perl code profiler, fixing many shortcomings in other tools and implementing many cool features. First of all it can be used as either a <i>line</i> profiler, a <i>block</i> or a <i>subroutine</i> profiler, all at once. It can also use sub-microsecond (100ns) resolution on systems which provide <code>clock_gettime()</code>. It can be started and stopped even by the program being profiled. It&#39;s a one-line entry to profile <code>mod_perl</code> applications. It&#39;s written in <code>c</code> and is probably the fastest profiler available for Perl. The list of coolness just goes on. Enough of that, let&#39;s see how to it works - just use the familiar <code>-d</code> switch to plug it in and run the code.</p>

<pre><code class="plaintext">$&gt; perl -d:NYTProf wordmatch -f perl5db.pl

wordmatch report for perl5db.pl:
lines in file: 9427
words in file: 50243
words with special (non-word) characters: 20480
words with only special (non-word) characters: 7790
words with only consonants: 4801
words with only capital letters: 1316
words with only vowels: 1701</code></pre>

<p><code>NYTProf</code> will generate a report database into the file <i>nytprof.out</i> by default. Human readable reports can be generated from here by using the supplied <code>nytprofhtml</code> (HTML output) and <code>nytprofcsv</code> (CSV output) programs. We&#39;ve used the Unix system <code>html2text</code> utility to convert the <i>nytprof/index.html</i> file for convenience here.</p>

<pre><code class="plaintext">$&gt; html2text nytprof/index.html

Performance Profile Index
For wordmatch
  Run on Fri Sep 26 13:46:39 2008
Reported on Fri Sep 26 13:47:23 2008

         Top 15 Subroutines -- ordered by exclusive time
|Calls |P |F |Inclusive|Exclusive|Subroutine                          |
|      |  |  |Time     |Time     |                                    |
|251215|5 |1 |13.09263 |10.47692 |main::              |matches        |
|260642|2 |1 |2.71199  |2.71199  |main::              |debug          |
|1     |1 |1 |0.21404  |0.21404  |main::              |report         |
|2     |2 |2 |0.00511  |0.00511  |XSLoader::          |load (xsub)    |
|14    |14|7 |0.00304  |0.00298  |Exporter::          |import         |
|3     |1 |1 |0.00265  |0.00254  |Exporter::          |as_heavy       |
|10    |10|4 |0.00140  |0.00140  |vars::              |import         |
|13    |13|1 |0.00129  |0.00109  |constant::          |import         |
|1     |1 |1 |0.00360  |0.00096  |FileHandle::        |import         |
|3     |3 |3 |0.00086  |0.00074  |warnings::register::|import         |
|9     |3 |1 |0.00036  |0.00036  |strict::            |bits           |
|13    |13|13|0.00032  |0.00029  |strict::            |import         |
|2     |2 |2 |0.00020  |0.00020  |warnings::          |import         |
|2     |1 |1 |0.00020  |0.00020  |Getopt::Long::      |ParseOptionSpec|
|7     |7 |6 |0.00043  |0.00020  |strict::            |unimport       |

For more information see the full list of 189 subroutines.</code></pre>

<p>The first part of the report already shows the critical information regarding which subroutines are using the most time. The next gives some statistics about the source files profiled.</p>

<pre><code class="plaintext">        Source Code Files -- ordered by exclusive time then name
|Stmts  |Exclusive|Avg.   |Reports                     |Source File         |
|       |Time     |       |                            |                    |
|2699761|15.66654 |6e-06  |line   .    block   .    sub|wordmatch           |
|35     |0.02187  |0.00062|line   .    block   .    sub|IO/Handle.pm        |
|274    |0.01525  |0.00006|line   .    block   .    sub|Getopt/Long.pm      |
|20     |0.00585  |0.00029|line   .    block   .    sub|Fcntl.pm            |
|128    |0.00340  |0.00003|line   .    block   .    sub|Exporter/Heavy.pm   |
|42     |0.00332  |0.00008|line   .    block   .    sub|IO/File.pm          |
|261    |0.00308  |0.00001|line   .    block   .    sub|Exporter.pm         |
|323    |0.00248  |8e-06  |line   .    block   .    sub|constant.pm         |
|12     |0.00246  |0.00021|line   .    block   .    sub|File/Spec/Unix.pm   |
|191    |0.00240  |0.00001|line   .    block   .    sub|vars.pm             |
|77     |0.00201  |0.00003|line   .    block   .    sub|FileHandle.pm       |
|12     |0.00198  |0.00016|line   .    block   .    sub|Carp.pm             |
|14     |0.00175  |0.00013|line   .    block   .    sub|Symbol.pm           |
|15     |0.00130  |0.00009|line   .    block   .    sub|IO.pm               |
|22     |0.00120  |0.00005|line   .    block   .    sub|IO/Seekable.pm      |
|198    |0.00085  |4e-06  |line   .    block   .    sub|warnings/register.pm|
|114    |0.00080  |7e-06  |line   .    block   .    sub|strict.pm           |
|47     |0.00068  |0.00001|line   .    block   .    sub|warnings.pm         |
|27     |0.00054  |0.00002|line   .    block   .    sub|overload.pm         |
|9      |0.00047  |0.00005|line   .    block   .    sub|SelectSaver.pm      |
|13     |0.00045  |0.00003|line   .    block   .    sub|File/Spec.pm        |
|2701595|15.73869 |       |Total                       |
|128647 |0.74946  |       |Average                     |
|       |0.00201  |0.00003|Median                      |
|       |0.00121  |0.00003|Deviation                   |

Report produced by the NYTProf 2.03 Perl profiler, developed by Tim Bunce and
Adam Kaplan.</code></pre>

<p>At this point, if you&#39;re using the <i>html</i> report, you can click through the various links to bore down into each subroutine and each line of code. Because we&#39;re using the text reporting here, and there&#39;s a whole directory full of reports built for each source file, we&#39;ll just display a part of the corresponding <i>wordmatch-line.html</i> file, sufficient to give an idea of the sort of output you can expect from this cool tool.</p>

<pre><code>$&gt; html2text nytprof/wordmatch-line.html

Performance Profile -- -block view-.-line view-.-sub view-
For wordmatch
Run on Fri Sep 26 13:46:39 2008
Reported on Fri Sep 26 13:47:22 2008

File wordmatch

 Subroutines -- ordered by exclusive time
|Calls |P|F|Inclusive|Exclusive|Subroutine    |
|      | | |Time     |Time     |              |
|251215|5|1|13.09263 |10.47692 |main::|matches|
|260642|2|1|2.71199  |2.71199  |main::|debug  |
|1     |1|1|0.21404  |0.21404  |main::|report |
|0     |0|0|0        |0        |main::|BEGIN  |


|Line|Stmts.|Exclusive|Avg.   |Code                                           |
|    |      |Time     |       |                                               |
|1   |      |         |       |#!/usr/bin/perl                                |
|2   |      |         |       |                                               |
|    |      |         |       |use strict;                                    |
|3   |3     |0.00086  |0.00029|# spent 0.00003s making 1 calls to strict::    |
|    |      |         |       |import                                         |
|    |      |         |       |use warnings;                                  |
|4   |3     |0.01563  |0.00521|# spent 0.00012s making 1 calls to warnings::  |
|    |      |         |       |import                                         |
|5   |      |         |       |                                               |
|6   |      |         |       |=head1 NAME                                    |
|7   |      |         |       |                                               |
|8   |      |         |       |filewords - word analysis of input file        |
&lt;...snip...&gt;
|62  |1     |0.00445  |0.00445|print report( %count );                        |
|    |      |         |       |# spent 0.21404s making 1 calls to main::report|
|63  |      |         |       |                                               |
|    |      |         |       |# spent 23.56955s (10.47692+2.61571) within    |
|    |      |         |       |main::matches which was called 251215 times,   |
|    |      |         |       |avg 0.00005s/call: # 50243 times               |
|    |      |         |       |(2.12134+0.51939s) at line 57 of wordmatch, avg|
|    |      |         |       |0.00005s/call # 50243 times (2.17735+0.54550s) |
|64  |      |         |       |at line 56 of wordmatch, avg 0.00005s/call #   |
|    |      |         |       |50243 times (2.10992+0.51797s) at line 58 of   |
|    |      |         |       |wordmatch, avg 0.00005s/call # 50243 times     |
|    |      |         |       |(2.12696+0.51598s) at line 55 of wordmatch, avg|
|    |      |         |       |0.00005s/call # 50243 times (1.94134+0.51687s) |
|    |      |         |       |at line 54 of wordmatch, avg 0.00005s/call     |
|    |      |         |       |sub matches {                                  |
&lt;...snip...&gt;
|102 |      |         |       |                                               |
|    |      |         |       |# spent 2.71199s within main::debug which was  |
|    |      |         |       |called 260642 times, avg 0.00001s/call: #      |
|    |      |         |       |251215 times (2.61571+0s) by main::matches at  |
|103 |      |         |       |line 74 of wordmatch, avg 0.00001s/call # 9427 |
|    |      |         |       |times (0.09628+0s) at line 50 of wordmatch, avg|
|    |      |         |       |0.00001s/call                                  |
|    |      |         |       |sub debug {                                    |
|104 |260642|0.58496  |2e-06  |my $message = shift;                           |
|105 |      |         |       |                                               |
|106 |260642|1.09917  |4e-06  |if ( $debug ) {                                |
|107 |      |         |       |print STDERR &quot;DBG: $message\n&quot;;                |
|108 |      |         |       |}                                              |
|109 |      |         |       |}                                              |
|110 |      |         |       |                                               |
|111 |1     |0.01501  |0.01501|exit 0;                                        |
|112 |      |         |       |                                               |</code></pre>

<p>Oodles of very useful information in there - this seems to be the way forward.</p>

<p>See also <code><a href="./Devel::NYTProf::Apache.html">Devel::NYTProf::Apache</a></code> which hooks <code>Devel::NYTProf</code> into <code>mod_perl</code>.</p>

<h1 id="SORTING"><a class="permalink" href="perlperf.html#SORTING">#</a>SORTING</h1>

<p>Perl modules are not the only tools a performance analyst has at their disposal, system tools like <code>time</code> should not be overlooked as the next example shows, where we take a quick look at sorting. Many books, theses and articles, have been written about efficient sorting algorithms, and this is not the place to repeat such work, there&#39;s several good sorting modules which deserve taking a look at too: <code>Sort::Maker</code>, <code>Sort::Key</code> spring to mind. However, it&#39;s still possible to make some observations on certain Perl specific interpretations on issues relating to sorting data sets and give an example or two with regard to how sorting large data volumes can effect performance. Firstly, an often overlooked point when sorting large amounts of data, one can attempt to reduce the data set to be dealt with and in many cases <code>grep()</code> can be quite useful as a simple filter:</p>

<pre><code>@data = sort grep { /$filter/ } @incoming</code></pre>

<p>A command such as this can vastly reduce the volume of material to actually sort through in the first place, and should not be too lightly disregarded purely on the basis of its simplicity. The <code>KISS</code> principle is too often overlooked - the next example uses the simple system <code>time</code> utility to demonstrate. Let&#39;s take a look at an actual example of sorting the contents of a large file, an apache logfile would do. This one has over a quarter of a million lines, is 50M in size, and a snippet of it looks like this:</p>

<p># logfile</p>

<pre><code class="plaintext">188.209-65-87.adsl-dyn.isp.belgacom.be - - [08/Feb/2007:12:57:16 +0000] &quot;GET /favicon.ico HTTP/1.1&quot; 404 209 &quot;-&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
188.209-65-87.adsl-dyn.isp.belgacom.be - - [08/Feb/2007:12:57:16 +0000] &quot;GET /favicon.ico HTTP/1.1&quot; 404 209 &quot;-&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
151.56.71.198 - - [08/Feb/2007:12:57:41 +0000] &quot;GET /suse-on-vaio.html HTTP/1.1&quot; 200 2858 &quot;http://www.linux-on-laptops.com/sony.html&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1&quot;
151.56.71.198 - - [08/Feb/2007:12:57:42 +0000] &quot;GET /data/css HTTP/1.1&quot; 404 206 &quot;http://www.rfi.net/suse-on-vaio.html&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1&quot;
151.56.71.198 - - [08/Feb/2007:12:57:43 +0000] &quot;GET /favicon.ico HTTP/1.1&quot; 404 209 &quot;-&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1&quot;
217.113.68.60 - - [08/Feb/2007:13:02:15 +0000] &quot;GET / HTTP/1.1&quot; 304 - &quot;-&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
217.113.68.60 - - [08/Feb/2007:13:02:16 +0000] &quot;GET /data/css HTTP/1.1&quot; 404 206 &quot;http://www.rfi.net/&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] &quot;GET /suse-on-vaio.html HTTP/1.1&quot; 200 2858 &quot;http://www.linux-on-laptops.com/sony.html&quot; &quot;Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)&quot;
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] &quot;GET /data/css HTTP/1.1&quot; 404 206 &quot;http://www.rfi.net/suse-on-vaio.html&quot; &quot;Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)&quot;
debora.to.isac.cnr.it - - [08/Feb/2007:13:03:58 +0000] &quot;GET /favicon.ico HTTP/1.1&quot; 404 209 &quot;-&quot; &quot;Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.0 (like Gecko)&quot;
195.24.196.99 - - [08/Feb/2007:13:26:48 +0000] &quot;GET / HTTP/1.0&quot; 200 3309 &quot;-&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9&quot;
195.24.196.99 - - [08/Feb/2007:13:26:58 +0000] &quot;GET /data/css HTTP/1.0&quot; 404 206 &quot;http://www.rfi.net/&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9&quot;
195.24.196.99 - - [08/Feb/2007:13:26:59 +0000] &quot;GET /favicon.ico HTTP/1.0&quot; 404 209 &quot;-&quot; &quot;Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9&quot;
crawl1.cosmixcorp.com - - [08/Feb/2007:13:27:57 +0000] &quot;GET /robots.txt HTTP/1.0&quot; 200 179 &quot;-&quot; &quot;voyager/1.0&quot;
crawl1.cosmixcorp.com - - [08/Feb/2007:13:28:25 +0000] &quot;GET /links.html HTTP/1.0&quot; 200 3413 &quot;-&quot; &quot;voyager/1.0&quot;
fhm226.internetdsl.tpnet.pl - - [08/Feb/2007:13:37:32 +0000] &quot;GET /suse-on-vaio.html HTTP/1.1&quot; 200 2858 &quot;http://www.linux-on-laptops.com/sony.html&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
fhm226.internetdsl.tpnet.pl - - [08/Feb/2007:13:37:34 +0000] &quot;GET /data/css HTTP/1.1&quot; 404 206 &quot;http://www.rfi.net/suse-on-vaio.html&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)&quot;
80.247.140.134 - - [08/Feb/2007:13:57:35 +0000] &quot;GET / HTTP/1.1&quot; 200 3309 &quot;-&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)&quot;
80.247.140.134 - - [08/Feb/2007:13:57:37 +0000] &quot;GET /data/css HTTP/1.1&quot; 404 206 &quot;http://www.rfi.net&quot; &quot;Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)&quot;
pop.compuscan.co.za - - [08/Feb/2007:14:10:43 +0000] &quot;GET / HTTP/1.1&quot; 200 3309 &quot;-&quot; &quot;www.clamav.net&quot;
livebot-207-46-98-57.search.live.com - - [08/Feb/2007:14:12:04 +0000] &quot;GET /robots.txt HTTP/1.0&quot; 200 179 &quot;-&quot; &quot;msnbot/1.0 (+http://search.msn.com/msnbot.htm)&quot;
livebot-207-46-98-57.search.live.com - - [08/Feb/2007:14:12:04 +0000] &quot;GET /html/oracle.html HTTP/1.0&quot; 404 214 &quot;-&quot; &quot;msnbot/1.0 (+http://search.msn.com/msnbot.htm)&quot;
dslb-088-064-005-154.pools.arcor-ip.net - - [08/Feb/2007:14:12:15 +0000] &quot;GET / HTTP/1.1&quot; 200 3309 &quot;-&quot; &quot;www.clamav.net&quot;
196.201.92.41 - - [08/Feb/2007:14:15:01 +0000] &quot;GET / HTTP/1.1&quot; 200 3309 &quot;-&quot; &quot;MOT-L7/08.B7.DCR MIB/2.2.1 Profile/MIDP-2.0 Configuration/CLDC-1.1&quot;</code></pre>

<p>The specific task here is to sort the 286,525 lines of this file by Response Code, Query, Browser, Referring Url, and lastly Date. One solution might be to use the following code, which iterates over the files given on the command-line.</p>

<p># sort-apache-log</p>

<pre><code>#!/usr/bin/perl -n

use strict;
use warnings;

my @data;

LINE:
while ( &lt;&gt; ) {
    my $line = $_;
    if (
        $line =~ m/^(
            ([\w\.\-]+)             # client
            \s*-\s*-\s*\[
            ([^]]+)                 # date
            \]\s*&quot;\w+\s*
            (\S+)                   # query
            [^&quot;]+&quot;\s*
            (\d+)                   # status
            \s+\S+\s+&quot;[^&quot;]*&quot;\s+&quot;
            ([^&quot;]*)                 # browser
            &quot;
            .*
        )$/x
    ) {
        my @chunks = split(/ +/, $line);
        my $ip      = $1;
        my $date    = $2;
        my $query   = $3;
        my $status  = $4;
        my $browser = $5;

        push(@data, [$ip, $date, $query, $status, $browser, $line]);
    }
}

my @sorted = sort {
    $a-&gt;[3] cmp $b-&gt;[3]
            ||
    $a-&gt;[2] cmp $b-&gt;[2]
            ||
    $a-&gt;[0] cmp $b-&gt;[0]
            ||
    $a-&gt;[1] cmp $b-&gt;[1]
            ||
    $a-&gt;[4] cmp $b-&gt;[4]
} @data;

foreach my $data ( @sorted ) {
    print $data-&gt;[5];
}

exit 0;</code></pre>

<p>When running this program, redirect <code>STDOUT</code> so it is possible to check the output is correct from following test runs and use the system <code>time</code> utility to check the overall runtime.</p>

<pre><code class="plaintext">$&gt; time ./sort-apache-log logfile &gt; out-sort

real    0m17.371s
user    0m15.757s
sys     0m0.592s</code></pre>

<p>The program took just over 17 wallclock seconds to run. Note the different values <code>time</code> outputs, it&#39;s important to always use the same one, and to not confuse what each one means.</p>

<dl>

<dt id="Elapsed-Real-Time"><a class="permalink" href="perlperf.html#Elapsed-Real-Time">#</a><a id="Elapsed"></a>Elapsed Real Time</dt>
<dd>

<p>The overall, or wallclock, time between when <code>time</code> was called, and when it terminates. The elapsed time includes both user and system times, and time spent waiting for other users and processes on the system. Inevitably, this is the most approximate of the measurements given.</p>

</dd>
<dt id="User-CPU-Time"><a class="permalink" href="perlperf.html#User-CPU-Time">#</a><a id="User"></a>User CPU Time</dt>
<dd>

<p>The user time is the amount of time the entire process spent on behalf of the user on this system executing this program.</p>

</dd>
<dt id="System-CPU-Time"><a class="permalink" href="perlperf.html#System-CPU-Time">#</a><a id="System"></a>System CPU Time</dt>
<dd>

<p>The system time is the amount of time the kernel itself spent executing routines, or system calls, on behalf of this process user.</p>

</dd>
</dl>

<p>Running this same process as a <code>Schwarzian Transform</code> it is possible to eliminate the input and output arrays for storing all the data, and work on the input directly as it arrives too. Otherwise, the code looks fairly similar:</p>

<p># sort-apache-log-schwarzian</p>

<pre><code>#!/usr/bin/perl -n

use strict;
use warnings;

print

    map $_-&gt;[0] =&gt;

    sort {
        $a-&gt;[4] cmp $b-&gt;[4]
                ||
        $a-&gt;[3] cmp $b-&gt;[3]
                ||
        $a-&gt;[1] cmp $b-&gt;[1]
                ||
        $a-&gt;[2] cmp $b-&gt;[2]
                ||
        $a-&gt;[5] cmp $b-&gt;[5]
    }
    map  [ $_, m/^(
        ([\w\.\-]+)             # client
        \s*-\s*-\s*\[
        ([^]]+)                 # date
        \]\s*&quot;\w+\s*
        (\S+)                   # query
        [^&quot;]+&quot;\s*
        (\d+)                   # status
        \s+\S+\s+&quot;[^&quot;]*&quot;\s+&quot;
        ([^&quot;]*)                 # browser
        &quot;
        .*
    )$/xo ]

    =&gt; &lt;&gt;;

exit 0;</code></pre>

<p>Run the new code against the same logfile, as above, to check the new time.</p>

<pre><code class="plaintext">$&gt; time ./sort-apache-log-schwarzian logfile &gt; out-schwarz

real    0m9.664s
user    0m8.873s
sys     0m0.704s</code></pre>

<p>The time has been cut in half, which is a respectable speed improvement by any standard. Naturally, it is important to check the output is consistent with the first program run, this is where the Unix system <code>cksum</code> utility comes in.</p>

<pre><code class="plaintext">$&gt; cksum out-sort out-schwarz
3044173777 52029194 out-sort
3044173777 52029194 out-schwarz</code></pre>

<p>BTW. Beware too of pressure from managers who see you speed a program up by 50% of the runtime once, only to get a request one month later to do the same again (true story) - you&#39;ll just have to point out you&#39;re only human, even if you are a Perl programmer, and you&#39;ll see what you can do...</p>

<h1 id="LOGGING"><a class="permalink" href="perlperf.html#LOGGING">#</a>LOGGING</h1>

<p>An essential part of any good development process is appropriate error handling with appropriately informative messages, however there exists a school of thought which suggests that log files should be <i>chatty</i>, as if the chain of unbroken output somehow ensures the survival of the program. If speed is in any way an issue, this approach is wrong.</p>

<p>A common sight is code which looks something like this:</p>

<pre><code>logger-&gt;debug( &quot;A logging message via process-id: $$ INC: &quot;
                                                      . Dumper(\%INC) )</code></pre>

<p>The problem is that this code will always be parsed and executed, even when the debug level set in the logging configuration file is zero. Once the debug() subroutine has been entered, and the internal <code>$debug</code> variable confirmed to be zero, for example, the message which has been sent in will be discarded and the program will continue. In the example given though, the <code>\%INC</code> hash will already have been dumped, and the message string constructed, all of which work could be bypassed by a debug variable at the statement level, like this:</p>

<pre><code>logger-&gt;debug( &quot;A logging message via process-id: $$ INC: &quot;
                                           . Dumper(\%INC) ) if $DEBUG;</code></pre>

<p>This effect can be demonstrated by setting up a test script with both forms, including a <code>debug()</code> subroutine to emulate typical <code>logger()</code> functionality.</p>

<p># ifdebug</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

use Benchmark;
use Data::Dumper;
my $DEBUG = 0;

sub debug {
    my $msg = shift;

    if ( $DEBUG ) {
        print &quot;DEBUG: $msg\n&quot;;
    }
};

timethese(100000, {
        &#39;debug&#39;       =&gt; sub {
            debug( &quot;A $0 logging message via process-id: $$&quot; . Dumper(\%INC) )
        },
        &#39;ifdebug&#39;  =&gt; sub {
            debug( &quot;A $0 logging message via process-id: $$&quot; . Dumper(\%INC) ) if $DEBUG
        },
});</code></pre>

<p>Let&#39;s see what <code>Benchmark</code> makes of this:</p>

<pre><code class="plaintext">$&gt; perl ifdebug
Benchmark: timing 100000 iterations of constant, sub...
   ifdebug:  0 wallclock secs ( 0.01 usr +  0.00 sys =  0.01 CPU) @ 10000000.00/s (n=100000)
            (warning: too few iterations for a reliable count)
     debug: 14 wallclock secs (13.18 usr +  0.04 sys = 13.22 CPU) @ 7564.30/s (n=100000)</code></pre>

<p>In the one case the code, which does exactly the same thing as far as outputting any debugging information is concerned, in other words nothing, takes 14 seconds, and in the other case the code takes one hundredth of a second. Looks fairly definitive. Use a <code>$DEBUG</code> variable BEFORE you call the subroutine, rather than relying on the smart functionality inside it.</p>

<h2 id="Logging-if-DEBUG-(constant)"><a class="permalink" href="perlperf.html#Logging-if-DEBUG-(constant)">#</a><a id="Logging"></a><a id="Logging-if-DEBUG-constant"></a>Logging if DEBUG (constant)</h2>

<p>It&#39;s possible to take the previous idea a little further, by using a compile time <code>DEBUG</code> constant.</p>

<p># ifdebug-constant</p>

<pre><code>#!/usr/bin/perl

use strict;
use warnings;

use Benchmark;
use Data::Dumper;
use constant
    DEBUG =&gt; 0
;

sub debug {
    if ( DEBUG ) {
        my $msg = shift;
        print &quot;DEBUG: $msg\n&quot;;
    }
};

timethese(100000, {
        &#39;debug&#39;       =&gt; sub {
            debug( &quot;A $0 logging message via process-id: $$&quot; . Dumper(\%INC) )
        },
        &#39;constant&#39;  =&gt; sub {
            debug( &quot;A $0 logging message via process-id: $$&quot; . Dumper(\%INC) ) if DEBUG
        },
});</code></pre>

<p>Running this program produces the following output:</p>

<pre><code class="plaintext">$&gt; perl ifdebug-constant
Benchmark: timing 100000 iterations of constant, sub...
  constant:  0 wallclock secs (-0.00 usr +  0.00 sys = -0.00 CPU) @ -7205759403792793600000.00/s (n=100000)
            (warning: too few iterations for a reliable count)
       sub: 14 wallclock secs (13.09 usr +  0.00 sys = 13.09 CPU) @ 7639.42/s (n=100000)</code></pre>

<p>The <code>DEBUG</code> constant wipes the floor with even the <code>$debug</code> variable, clocking in at minus zero seconds, and generates a &quot;warning: too few iterations for a reliable count&quot; message into the bargain. To see what is really going on, and why we had too few iterations when we thought we asked for 100000, we can use the very useful <code>B::Deparse</code> to inspect the new code:</p>

<pre><code>$&gt; perl -MO=Deparse ifdebug-constant

use Benchmark;
use Data::Dumper;
use constant (&#39;DEBUG&#39;, 0);
sub debug {
    use warnings;
    use strict &#39;refs&#39;;
    0;
}
use warnings;
use strict &#39;refs&#39;;
timethese(100000, {&#39;sub&#39;, sub {
    debug &quot;A $0 logging message via process-id: $$&quot; . Dumper(\%INC);
}
, &#39;constant&#39;, sub {
    0;
}
});
ifdebug-constant syntax OK</code></pre>

<p>The output shows the constant() subroutine we&#39;re testing being replaced with the value of the <code>DEBUG</code> constant: zero. The line to be tested has been completely optimized away, and you can&#39;t get much more efficient than that.</p>

<h1 id="POSTSCRIPT"><a class="permalink" href="perlperf.html#POSTSCRIPT">#</a>POSTSCRIPT</h1>

<p>This document has provided several way to go about identifying hot-spots, and checking whether any modifications have improved the runtime of the code.</p>

<p>As a final thought, remember that it&#39;s not (at the time of writing) possible to produce a useful program which will run in zero or negative time and this basic principle can be written as: <i>useful programs are slow</i> by their very definition. It is of course possible to write a nearly instantaneous program, but it&#39;s not going to do very much, here&#39;s a very efficient one:</p>

<pre><code class="plaintext">$&gt; perl -e 0</code></pre>

<p>Optimizing that any further is a job for <code>p5p</code>.</p>

<h1 id="SEE-ALSO"><a class="permalink" href="perlperf.html#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1>

<p>Further reading can be found using the modules and links below.</p>

<h2 id="PERLDOCS"><a class="permalink" href="perlperf.html#PERLDOCS">#</a>PERLDOCS</h2>

<p>For example: <code>perldoc -f sort</code>.</p>

<p><a href="perlfaq4.html">perlfaq4</a>.</p>

<p><a href="perlfork.html">perlfork</a>, <a href="perlfunc.html">perlfunc</a>, <a href="perlretut.html">perlretut</a>, <a href="perlthrtut.html">perlthrtut</a>.</p>

<p><a href="threads.html">threads</a>.</p>

<h2 id="MAN-PAGES"><a class="permalink" href="perlperf.html#MAN-PAGES">#</a><a id="MAN"></a>MAN PAGES</h2>

<p><code>time</code>.</p>

<h2 id="MODULES"><a class="permalink" href="perlperf.html#MODULES">#</a>MODULES</h2>

<p>It&#39;s not possible to individually showcase all the performance related code for Perl here, naturally, but here&#39;s a short list of modules from the CPAN which deserve further attention.</p>

<pre><code class="plaintext">Apache::DProf
Apache::SmallProf
Benchmark
DBIx::Profile
Devel::AutoProfiler
Devel::DProf
Devel::DProfLB
Devel::FastProf
Devel::GraphVizProf
Devel::NYTProf
Devel::NYTProf::Apache
Devel::Profiler
Devel::Profile
Devel::Profit
Devel::SmallProf
Devel::WxProf
POE::Devel::Profiler
Sort::Key
Sort::Maker</code></pre>

<h2 id="URLS"><a class="permalink" href="perlperf.html#URLS">#</a>URLS</h2>

<p>Very useful online reference material:</p>

<pre><code class="plaintext">http://www.ccl4.org/~nick/P/Fast_Enough/

http://www-128.ibm.com/developerworks/library/l-optperl.html

http://perlbuzz.com/2007/11/bind-output-variables-in-dbi-for-speed-and-safety.html

http://en.wikipedia.org/wiki/Performance_analysis

http://apache.perl.org/docs/1.0/guide/performance.html

http://perlgolf.sourceforge.net/

http://www.sysarch.com/Perl/sort_paper.html</code></pre>

<h1 id="AUTHOR"><a class="permalink" href="perlperf.html#AUTHOR">#</a>AUTHOR</h1>

<p>Richard Foley &lt;richard.foley@rfi.net&gt; Copyright (c) 2008</p>


      </div>
      <div id="footer">
        <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p>

<p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p>


      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
    <script src="../highlight.pack.js"></script>
    <script>hljs.highlightAll();</script>
  </body>
</html>
